package cn.xiehang.SoundSight;

import android.Manifest;
import android.animation.Animator;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.airbnb.lottie.LottieAnimationView;
import com.skydoves.androidbottombar.AndroidBottomBarView;
import com.skydoves.androidbottombar.BottomMenuItem;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.OkHttpClient;

public class FifthFragment extends Fragment {
    private OkHttpClient client;
    private ProgressDialog progressDialog;
    private MediaRecorder mediaRecorder;

    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private final String[] permissions = {Manifest.permission.RECORD_AUDIO};
    private String outputFile;
    private LottieAnimationView recordButton;
    private boolean isRecording = false; // 声明并初始化 isRecording

    private BottomMenuItem home;
    private BottomMenuItem profile;
    private BottomMenuItem settings;
    private BottomMenuItem mine;
    private AndroidBottomBarView bottomNavigationBar;
    private ViewPager2 viewPager;
    private Runnable runnable;
    private Handler handler = new Handler();
    private Button instruction;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载Fragment的布局文件
        View view = inflater.inflate(R.layout.fragment_fifth, container, false);
           instruction=view.findViewById(R.id.fifth_fragment_instructions_button);

           //设置点击事件
              instruction.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //显示文本框
                    TextView textView = view.findViewById(R.id.fifth_fragment_instruction);
                    if (textView.getVisibility() == View.INVISIBLE) {
                        textView.setVisibility(View.VISIBLE);
                    } else {
                        textView.setVisibility(View.INVISIBLE);
                    }
                }
              }
              );


            //获取ViewPager
            viewPager = view.findViewById(R.id.viewPager);

            List<Integer> imageList = Arrays.asList(
                    R.drawable.ic_fifth_normal,
                    R.drawable.ic_first_normal,
                    R.drawable.ic_fourth_normal
            );


            ImageAdapter adapter = new ImageAdapter(this,imageList);
            viewPager.setAdapter(adapter);
            // 设置自动轮播
            runnable = new Runnable() {
                @Override
                public void run() {
                    int currentItem = viewPager.getCurrentItem();
                    int totalItems = adapter.getItemCount();
                    int nextItem = (currentItem + 1) % totalItems;
                    viewPager.setCurrentItem(nextItem, true);
                    handler.postDelayed(this, 3000); // 3 秒后执行
                }
            };
            handler.postDelayed(runnable, 3000); // 3 秒后执行











        // 检查并请求权限
        if (checkPermissions()) {
            initializeRecorder(); // 权限已授予，初始化录音器
        } else {
            requestPermissions(); // 请求权限
        }

        LottieAnimationView recordButton = view.findViewById(R.id.recordButton);

        // 设置长按事件
        recordButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!isRecording) {
                    startRecording();
                    recordButton.playAnimation(); // 开始动画
                    isRecording = true;
                }
                return true; // 返回 true 表示消耗了长按事件
            }
        });

        // 设置触摸松开事件
        recordButton.setOnTouchListener((v, event) -> {
            if (isRecording && event.getAction() == android.view.MotionEvent.ACTION_UP) {
                stopRecording();
                //获取当前动画进度
                float currentProgress = recordButton.getProgress();
                // 从当前进度播放到 1.0f 结束
                recordButton.setMinAndMaxProgress(currentProgress, 1.0f);
                recordButton.addAnimatorListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {}

                    @Override
                    public void onAnimationEnd(Animator animation) {
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {}

                    @Override
                    public void onAnimationRepeat(Animator animation) {
                        //将动画区间设置为 0 到 1
                        recordButton.setMinAndMaxProgress(0f, 1f);
                        recordButton.cancelAnimation(); // 停止动画
                        recordButton.setProgress(0); // 重置进度为 0
                        isRecording = false;
                        //释放监视器
                        recordButton.removeAnimatorListener(this);
                    }
                });
            }
            return false; // 返回 false 以允许长按事件触发
        });
//        // 设置长按事件
//        recordButton.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                if (!isRecording) {
//                    startRecording();
//                    recordButton.setMinAndMaxProgress(0f, 0.8f);
//                    recordButton.playAnimation();
//                    isRecording = true;
//
//
//
//                    // 监听动画结束事件，实现 0.2f 到 0.8f 的循环
//                    recordButton.addAnimatorListener(new Animator.AnimatorListener() {
//                        @Override
//                        public void onAnimationStart(Animator animation) {}
//
//                        @Override
//                        public void onAnimationEnd(Animator animation) {
//                        }
//
//                        @Override
//                        public void onAnimationCancel(Animator animation) {}
//
//                        @Override
//                        public void onAnimationRepeat(Animator animation) {
//                            recordButton.setMinAndMaxProgress(0.3f, 0.7f);
//                            recordButton.playAnimation();
//                            //释放监视器
//                            recordButton.removeAnimatorListener(this);
//                        }
//                    });
//                }
//                return true; // 返回 true 表示消耗了长按事件
//            }
//        });
//
//// 设置触摸松开事件
//        recordButton.setOnTouchListener((v, event) -> {
//            if (isRecording && event.getAction() == android.view.MotionEvent.ACTION_UP) {
//                stopRecording();
//                isRecording = false;
//
//
//                // 获取当前动画进度
//                float currentProgress = recordButton.getProgress();
//
//                // 从当前进度播放到 1.0f 结束
//                recordButton.setMinAndMaxProgress(currentProgress, 1.0f);
//                recordButton.playAnimation();
//
//                // 监听动画结束事件，确保动画停留在 1.0f
//                recordButton.addAnimatorListener(new Animator.AnimatorListener() {
//                    @Override
//                    public void onAnimationStart(Animator animation) {}
//
//                    @Override
//                    public void onAnimationEnd(Animator animation) {
//                    }
//
//                    @Override
//                    public void onAnimationCancel(Animator animation) {}
//
//                    @Override
//                    public void onAnimationRepeat(Animator animation) {
//                        recordButton.setMinAndMaxProgress(0f, 1f);
//                        recordButton.cancelAnimation(); // 停止动画
//                        recordButton.setProgress(0); // 重置进度为 0
//                        isRecording = false;
//                    }
//                });
//            }
//            return false; // 返回 false 以允许长按事件触发
//        });



// Inflate the layout for this fragment
        return view;

    }
    private void startRecording() {
        try {
            // 重新初始化 MediaRecorder
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            // 获取当前日期
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
            // 创建日期文件夹
            // 获取外部存储的私有文件目录
//        File externalFilesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);

            // 或者使用 requireContext()，确保 Context 不为 null
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
            File appDir = new File(storageDir, "SoundSight"); // 在Music目录下创建你的应用文件夹

            if (!appDir.exists()) {
                appDir.mkdirs();
            }


            // 生成文件名
            int fileNumber = getNextFileNumber(storageDir,currentDate);
            File recordingFile = new File( appDir, currentDate+fileNumber + ".mp3");
            outputFile = recordingFile.getAbsolutePath();

            // 设置录音文件路径
            mediaRecorder.setOutputFile(outputFile);
            mediaRecorder.prepare();
            mediaRecorder.start();
            Context context = getContext();
            Toast.makeText(context, "录音开始", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取下一个文件序号
    private int getNextFileNumber(File directory,String filetime) {
        int maxNumber = 0;
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                String fileName = file.getName();
                if (fileName.endsWith(".mp3")&& fileName.startsWith(filetime)) { // 只处理以日期开头的文件
                    try {
                        // 获取文件名中的数字部分
                        String numberStr = fileName.substring(fileName.lastIndexOf(filetime) + filetime.length(), fileName.lastIndexOf(".mp3"));
                        int number = Integer.parseInt(numberStr);
                        if (number > maxNumber) {
                            maxNumber = number;
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return maxNumber + 1; // 返回最大序号 + 1
    }

    // 停止录音
    private void stopRecording() {
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null; // 释放后设置为 null
            Context context = getContext();

            if (getDuration(outputFile) < 3000) { // 3000 毫秒 = 3 秒
                deleteFile(outputFile);
                Toast.makeText(context, "录音文件无效（时长小于 3 秒）", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "录音文件已保存: " + outputFile, Toast.LENGTH_SHORT).show();
//                FileUploadClient fileUploadClient = new FileUploadClient();
//                boolean flage=fileUploadClient.send(outputFile);
//                if(flage){
//                    Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
//                }else{
//                    Toast.makeText(this, "上传失败", Toast.LENGTH_SHORT).show();
//                }
            }
        }
    }

    //获取录音文件时长
    private long getDuration(String filePath) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            retriever.release();
            return Long.parseLong(durationStr);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }
    // 删除文件
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                Log.d("FileDelete", "文件已删除: " + filePath);
            } else {
                Log.e("FileDelete", "文件删除失败: " + filePath);
                return false;
            }
        }
        return true;
    }



    // 检查权限是否已授予
    private boolean checkPermissions() {
        Context context = getContext();
        return ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
    }

    // 请求权限
    private void requestPermissions() {
        ActivityCompat.requestPermissions(requireActivity(),
                new String[]{Manifest.permission.RECORD_AUDIO},
                REQUEST_RECORD_AUDIO_PERMISSION);
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initializeRecorder(); // 权限已授予，初始化录音器
            } else {
                // 权限被拒绝，提示用户
                showPermissionDeniedMessage();
            }
        }
    }

    // 初始化录音器
    private void initializeRecorder() {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        outputFile = requireContext().getExternalCacheDir().getAbsolutePath() + "/recording.3gp";
        mediaRecorder.setOutputFile(outputFile);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    }


    // 显示权限被拒绝的提示
    private void showPermissionDeniedMessage() {
        // 可以使用 Toast 或 Snackbar 提示用户
        Context context = getContext();
        Toast.makeText(context, "录音权限被拒绝，无法使用录音功能", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 停止轮播
        handler.removeCallbacks(runnable);
        //删除轮播图片
        handler.removeCallbacksAndMessages(null);
        viewPager.setAdapter(null);
        }
        public static FifthFragment newInstance() {
            return new FifthFragment();
        }
    }




